<template>
  <search-list
    :api-url="url.SaleUserList"
    :option="searchOpt"
    :itemPerRow="8"
    @selection-change="selectionChange"
    :beforeQuery="beforeQuery"
    @getSearchData="getSearchData"
    ref="searchListRef"
  >
    <el-table-column type="selection"></el-table-column>
    <el-table-column label="头像/昵称" show-overflow-tooltip>
      <template #="scope">
        <img :src="scope.row.avatar" class="list-img" alt="" />
        {{ scope.row.nickname }}
      </template>
    </el-table-column>
    <el-table-column
      prop="username"
      label="真实姓名"
      show-overflow-tooltip
      align="center"
    ></el-table-column>
    <el-table-column
      prop="phone"
      label="手机号码"
      show-overflow-tooltip
      align="center"
    ></el-table-column>
    <el-table-column
      prop="superior"
      label="上级推广员"
      show-overflow-tooltip
      align="center"
    ></el-table-column>
    <el-table-column prop="customerCnt" label="累计客户（人）" show-overflow-tooltip align="center">
      <template #header>
        <el-tooltip class="item" effect="dark" content="被推广邀请并成功产生购买的用户数" placement="top">
          <span>累计客户（人）<i class="el-icon-question"></i></span>
        </el-tooltip>
      </template>
      <template #="scope">{{ scope.row.customerCnt }}人</template>
    </el-table-column>
    <el-table-column prop="viewCnt" label="累计查看（次数）" show-overflow-tooltip align="center">
      <template #header>
        <el-tooltip class="item" effect="dark" content="推广的页面累计被打开的次数" placement="top">
          <span>累计查看（次数）<i class="el-icon-question"></i></span>
        </el-tooltip>
      </template>
      <template #="scope">{{ scope.row.viewCnt }}次</template>
    </el-table-column>
    <el-table-column prop="bindCnt" label="当前绑定（人）" show-overflow-tooltip align="center">
      <template #header>
        <el-tooltip class="item" effect="dark" content="被邀请并成功登录绑定，且当前仍绑定着该推广员的用户数 (当绑定的用户绑定至其他推广员时，数字减1）" placement="top">
          <span>当前绑定（人）<i class="el-icon-question"></i></span>
        </el-tooltip>
      </template>
      <template #="scope">{{ scope.row.bindCnt }}人</template>
    </el-table-column>
    <el-table-column prop="regCnt" label="累计注册（人）" show-overflow-tooltip align="center">
      <template #header>
        <el-tooltip class="item" effect="dark" content="被邀请并完成注册登录的新用户数" placement="top">
          <span>累计注册（人）<i class="el-icon-question"></i></span>
        </el-tooltip>
      </template>
      <template #="scope">{{ scope.row.regCnt }}人</template>
    </el-table-column>
    <el-table-column
      prop="income"
      label="累计分佣（包含待结算）"
      show-overflow-tooltip
      align="center"
    >
      <template #="scope">
        <span v-if="scope.row.income">{{ scope.row.income }}元</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="createdAt"
      label="加入时间"
      show-overflow-tooltip
      align="center"
    ></el-table-column>
    <el-table-column label="操作" width="250">
      <template #="scope">
        <el-button type="primary" @click="detail(scope.row)">详情</el-button>
        <el-button type="success" v-if="scope.row.disabled" @click="blackList(0, scope.row)">
          移出黑名单
        </el-button>
        <el-button type="danger" v-else @click="blackList(1, scope.row)">加入黑名单</el-button>
      </template>
    </el-table-column>
    <template v-slot:btn-after class="btn-after">
      <el-button type="success" icon="el-icon-download" @click="exportList">导出列表</el-button>
      <el-button
        type="primary"
        icon="el-icon-edit"
        @click="blackList(1)"
        :disabled="state.multipleSelection.length === 0"
      >
        批量加入黑名单
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-edit"
        @click="blackList(0)"
        :disabled="state.multipleSelection.length === 0"
      >
        批量移出黑名单
      </el-button>
    </template>
  </search-list>
  <!-- 详情 -->
  <el-dialog v-model="detailVisible" title="详情" center width="90%" destroy-on-close="true">
    <!-- 卡片 -->
    <div class="detail-card">
      <el-row>
        <div class="detail-img">
          <img :src="state.personDetail.avatar || ''" alt="" />
          <span>{{ state.personDetail.nickname || '' }}</span>
        </div>
      </el-row>
      <el-row class="detail-item">
        <el-col :span="6">真实姓名：{{ state.personDetail.username || '' }}</el-col>
        <el-col :span="6">
          直接推广笔数：{{
            state.personDetail.saleCnt !== undefined ? state.personDetail.saleCnt : ''
          }}
        </el-col>
        <el-col :span="6">直接推广金额：{{ state.personDetail.payAmount + '元' || '' }}</el-col>
        <el-col :span="6">上级推广员：{{ state.personDetail.parentNickname || '无' }}</el-col>
      </el-row>
      <el-row class="detail-item">
        <el-col :span="6">
          性别：{{
            state.personDetail.sex === '1' ? '男' : state.personDetail.sex === '2' ? '女' : '未知'
          }}
        </el-col>
        <el-col :span="6">
          间接推广笔数：{{state.personDetail.indirectSaleCnt || 0}}
        </el-col>
        <el-col :span="6">间接推广金额：{{ state.personDetail.indirectPayAmount  || '0.00'}} 元</el-col>
        <el-col :span="6">加入时间：{{ state.personDetail.createdAt || '' }}</el-col>
      </el-row>
      <el-row class="detail-item">
        <el-col :span="6">手机号码：{{ state.personDetail.phone || '' }}</el-col>
        <el-col :span="6">
          累计分佣（包含待结算）：{{ state.personDetail.saleIncome || '' }}元
        </el-col>
      </el-row>
    </div>
    <!-- 切换 -->
    <el-tabs v-model="activeName">
      <!-- 这一段可以循环的 -->
      <!-- 0-直接累计客户 1-当前绑定 2-累计注册 3-间接累计客户 4-下级推广员 -->
      <el-tab-pane
        :label="
          state.totalData['type-0'] ? '累计客户(' + state.totalData['type-0'] + ')' : '累计客户(0)'
        "
        name="first"
      >
        <!-- 表格 -->
        <PersonTable :type="0" @getTotal="getTotal" :uuid="uuidInfo"></PersonTable>
      </el-tab-pane>
      <el-tab-pane
        :label="
          state.totalData['type-1'] ? '当前绑定(' + state.totalData['type-1'] + ')' : '当前绑定(0)'
        "
        name="second"
      >
        <!-- 表格 -->
        <PersonTable :type="1" @getTotal="getTotal" :uuid="uuidInfo"></PersonTable>
      </el-tab-pane>
      <el-tab-pane
        :label="
          state.totalData['type-2'] ? '累计注册(' + state.totalData['type-2'] + ')' : '累计注册(0)'
        "
        name="third"
      >
        <!-- 表格 -->
        <PersonTable :type="2" @getTotal="getTotal" :uuid="uuidInfo"></PersonTable>
      </el-tab-pane>
      <el-tab-pane
        :label="
          state.totalData['type-3'] ? '间接累计客户(' + state.totalData['type-3'] + ')' : '间接累计客户(0)'
        "
        name="four"
      >
        <!-- 表格 -->
        <PersonTable :type="3" @getTotal="getTotal" :uuid="uuidInfo"></PersonTable>
      </el-tab-pane>
      <el-tab-pane
        :label="
          state.totalData['type-4'] ? '下级推广员(' + state.totalData['type-4'] + ')' : '下级推广员(0)'
        "
        name="five"
      >
        <!-- 表格 -->
        <PersonTable :type="4" @getTotal="getTotal" :uuid="uuidInfo"></PersonTable>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>
<script>
  import { getCurrentInstance, onMounted, reactive, ref, watch, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import PersonTable from '@/components/PersonTable.vue';
  import dayjs from 'dayjs';
  // 这个就是事件总线哦
  import bus from '@/bus';
  export default {
    components: {
      PersonTable,
    },
    setup() {
      const {
        $url: url,
        $service: service,
        JSON_HEADER: JSON_HEADER,
        $selectFormat: selectFormat,
      } = getCurrentInstance().appContext.config.globalProperties;

      // data
      // 筛选
      const searchOpt = ref([
        {
          type: 'el-input',
          name: 'nickname',
          label: '分销员昵称',
        },
        {
          type: 'el-input',
          name: 'parent',
          label: '上级分销员',
        },
        {
          type: 'el-input',
          name: 'username',
          label: '分销员姓名',
        },
        {
          type: 'el-input',
          name: 'phone',
          label: '手机号码',
        },
        {
          type: 'el-date-picker',
          name: 'startTime',
          label: '加入时间',
        },
      ]);
      const detailVisible = ref(false);
      const activeName = ref('first');
      const searchListRef = ref(null);
      const uuidInfo = ref('');
      const state = reactive({
        // 选中
        multipleSelection: [],
        // 详情分销员数据
        personDetail: [],
        // 筛选的数据
        searchData: [],
        // 这里的书记用来保存总数
        totalData: {},
      });

      // methods
      // 得到总数
      bus.$on('getTotal', (data) => {
        let _ = data.split(':');
        state.totalData[_[0]] = _[1];
      });
      // 表格多选
      const selectionChange = (val) => {
        state.multipleSelection = [...val];
      };
      // 导出列表
      const exportList = () => {
        // console.log(state.searchData)
        service.SaleUserListDownload(state.searchData, { responseType: 'blob' }).then((res) => {
          var blob = new Blob([res], { type: 'application/vnd.ms-excel' });
          let url = window.URL.createObjectURL(blob);
          let el = document.createElement('a');
          document.body.appendChild(el);
          el.href = url;
          el.download = '分销员列表' + '.xlsx';
          el.click();
          window.URL.revokeObjectURL(url);
        });
      };
      // 加入或者移出黑名单----1加入，0移出
      const blackList = (tag, item) => {
        ElMessageBox.confirm('确定执行此操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            service
              .SaleUserDisable({
                uids: item
                  ? item.uuid
                  : state.multipleSelection
                      .map((item) => {
                        return item.uuid;
                      })
                      .join(','),
                disable: tag,
              })
              .then((res) => {
                ElMessage({ showClose: true, message: '设置成功！', type: 'success' });
                searchListRef.value.getList();
              });
          })
          .catch(() => {});
      };
      // 详情
      const detail = (item) => {
        // 每次打开详情的时候记得清空总数那里
        state.totalData = [];

        uuidInfo.value = item.uuid;
        detailVisible.value = true;
        service.SaleUserDetail({ uuid: item.uuid }).then((res) => {
          state.personDetail = res;
        });
      };
      // 搜索之前
      const beforeQuery = ({ searchInfo }) => {
        // 这里就得处理element的坑(转格式)
        for (let key in searchInfo) {
          if (searchInfo[key] instanceof Date) {
            searchInfo[key] = dayjs(searchInfo.startTime).format('YYYY-MM-DD HH:mm:ss');
          }
        }
      };
      // 得到搜索数据
      const getSearchData = (val) => {
        state.searchData = val;
      };

      // life
      onMounted(() => {});

      return {
        url,
        service,
        JSON_HEADER,
        selectFormat,
        searchOpt,
        // data
        detailVisible,
        activeName,
        searchListRef,
        uuidInfo,
        state,
        // methods
        selectionChange,
        exportList,
        blackList,
        detail,
        beforeQuery,
        getSearchData,
      };
    },
  };
</script>
<style lang="less" scoped>
  .list-img {
    width: 39px;
    height: 39px;
    border-radius: 50%;
    vertical-align: middle;
  }
  // 详情卡片区
  .detail-card {
    width: 100%;
    height: 150px;
    background-color: #ddd;
    border-radius: 10px;
    .detail-img {
      margin: 10px;
      img {
        width: 39px;
        height: 39px;
        border-radius: 50%;
        vertical-align: middle;
      }
      span {
        margin-left: 15px;
      }
    }
    .detail-item {
      margin: 6px 20px 0px 20px;
    }
  }
</style>
